#!/bin/sh

# fail if any commands fails
set -e
# debug log
#set -x

show_usage (){
    printf "Usage: $0 [options [parameters]]\n"
    printf "\n"
    printf "Mandatory options:\n"
    printf " -i|--iwad          [doom|doom2|tnt|plutonia|heretic|hexen|chex3]\n"
    printf " -l|--map-limit     [none|vanilla|nolimit|boom|zdoom]\n"
    printf "\n"
    printf "Options:\n"
    printf " -d|--game-dir      [/path/to/doom/base/directory] (Optional, default: '~/games/doom')\n"
    printf " -h|--help, Print help\n"

exit
}

if [ "$1" = "--help" ] || [ "$1" = "-h" ]; then
  show_usage
fi
if [ -z "$1" ]; then
  show_usage
fi

while [ -n "$1" ]; do
  case "$1" in
     --game-dir|-d)
        shift
        echo "INFO: param - game directory: $1"
        param_game_dir=$1
        ;;
     --iwad|-i)
        shift
        echo "INFO: param - iwad: $1"
        param_iwad=$1
        ;;
     --map-limit|-l)
        shift
        echo "INFO: param - map limit: $1"
        param_map_limit=$1
         ;;
     *)
        show_usage
        ;;
  esac
shift
done


### Configuration
if [ -z "$param_game_dir" ]; then
      param_game_dir="$HOME/games/doom"
fi
config_script_dir="$(pwd $(dirname $0))"
config_iwad_dir=$param_game_dir/wads/iwads
if [ -z "$param_iwad" ]; then
  echo "ERROR: iwad parameter is mandatory"
  exit 1
fi
if [ -z "$param_map_limit" ]; then
  echo "ERROR: map limit parameter is mandatory"
  exit 1
fi


### check parameter values
doom_game="doom doom2 tnt plutonia heretic hexen chex3"
echo "$doom_game" | tr ' ' '\n' | while read -r item; do
  if [ "$item" = "$param_iwad" ]; then touch match; fi
done
if [ ! -f match ]; then echo "ERROR: $param_iwad is not a valid option, valid options are: $doom_game"; exit 1; fi; rm match

map_limit="none vanilla nolimit boom zdoom"
echo "$map_limit" | tr ' ' '\n' | while read -r item; do
  if [ "$item" = "$param_map_limit" ]; then touch match; fi
done
if [ ! -f match ]; then echo "ERROR: $param_map_limit is not a valid option, valid options are: $map_limit"; exit 1; fi; rm match


# generate map
if [ ! -f ~/src/Obsidian/obsidian ]; then
  echo "Obsidian not available in '~/src/Obsidian/' directory. Please compile it and try again"
  exit 1
fi
echo "INFO: creating new obsidian map..."
config_pwad_file="${param_game_dir}/wads/obsidian/obsidian_${param_iwad}.wad"
config_obsidian_file="${param_game_dir}/tools/obsidian/configs/${param_iwad}_${param_map_limit}.txt"
if [ ! -f "$config_obsidian_file" ]; then echo "ERROR: file $config_obsidian_file don't exists. valid files are"; ls -lahF "$param_game_dir"/tools/obsidian/configs/; exit 1; fi
cd ~/src/Obsidian/ && ./obsidian --install ~/src/Obsidian/ --batch "$config_pwad_file" --load "$config_obsidian_file"
cd -
echo "INFO: new obsidian map created... ${config_pwad_file}"